<?php
// 这是系统自动生成的公共文件
//递归排序
function set_recursion($result, $pid = 0, $format = "L ")
{
    /*记录排序后的类别数组*/
    static $list = array();

    foreach ($result as $k => $v) {
        if ($v['pid'] == $pid) {
            if ($pid != 0) {
                $v['title'] = $format . $v['title'];
            }
            /*将该类别的数据放入list中*/
            $list[] = $v;
            set_recursion($result, $v['id'], "  " . $format);
        }
    }

    return $list;
}

//读取权限节点列表
function get_admin_rule()
{
    $rule = \think\facade\Db::name('AdminRule')->order('create_time asc')->select()->toArray();
    return $rule;
}

//菜单父子关系排序，用于后台菜单
function get_admin_menus()
{
    if (get_cache('menu' . get_login_admin('id'))) {
        $list = get_cache('menu' . get_login_admin('id'));
    } else {
        $adminGroup = \think\facade\Db::name('AdminGroupAccess')->where(['uid' => get_login_admin('id')])->column('group_id');
        $adminMenu = \think\facade\Db::name('AdminGroup')->where('id', 'in', $adminGroup)->column('menus');
        $adminMenus = [];
        foreach ($adminMenu as $k => $v) {
            $v = explode(',', $v);
            $adminMenus = array_merge($adminMenus, $v);
        }
        $menu = \think\facade\Db::name('AdminMenu')->where('id', 'in', $adminMenus)->order('sort asc')->select()->toArray();
        $list = list_to_tree($menu);
        \think\facade\Cache::tag('adminMenu')->set('menu' . get_login_admin('id'), $list);
    }
    return $list;
}

// admin模块公共文件
//获取后台模块当前登录用户的信息
function get_login_admin($key = "")
{
    $session_admin = get_config('app.session_admin');
    if (\think\facade\Session::has($session_admin)) {
        $gougu_admin = \think\facade\Session::get($session_admin);
        if (!empty($key)) {
            if (isset($gougu_admin[$key])) {
                return $gougu_admin[$key];
            } else {
                return '';
            }
        } else {
            return $gougu_admin;
        }
    } else {
        return '';
    }
}

function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'list', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[$data[$pk]] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][$data[$pk]] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

function get_admin_menu()
{
    $menu = \think\facade\Db::name('AdminMenu')->order('sort asc')->select()->toArray();
    return $menu;
}

function get_admin_group_info($id)
{
    $group = \think\facade\Db::name('AdminGroup')->where(['id' => $id])->find();
    $group['rules'] = explode(',', $group['rules']);
    $group['menus'] = explode(',', $group['menus']);
    return $group;
}

function create_tree_list($pid, $arr, $group, &$tree = [])
{
    foreach ($arr as $key => $vo) {
        if ($key == 0) {
            $vo['spread'] = true;
        }
        if (!empty($group) and in_array($vo['id'], $group)) {
            $vo['checked'] = true;
        } else {
            $vo['checked'] = false;
        }
        if ($vo['pid'] == $pid) {
            $child = create_tree_list($vo['id'], $arr, $group);
            if ($child) {
                $vo['children'] = $child;
            }
            $tree[] = $vo;
        }
    }
    return $tree;
}

//获取指定管理员的信息
function get_admin($id)
{
    $admin = \think\facade\Db::name('Admin')->where(['id' => $id])->find();
    $admin['group_id'] = \think\facade\Db::name('AdminGroupAccess')->where(['uid' => $id])->column('group_id');
    return $admin;
}

//读取权限分组列表
function get_admin_group()
{
    $group = \think\facade\Db::name('AdminGroup')->order('create_time asc')->select()->toArray();
    return $group;
}

/**
 * PHP格式化字节大小
 * @param number $size      字节数
 * @param string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }

    return round($size, 2) . $delimiter . $units[$i];
}

//读取关键字列表
function get_keywords()
{
    $keywords = \think\facade\Db::name('Keywords')->where(['status' => 1])->order('create_time asc')->select();
    return $keywords;
}

/**
 * 管理员操作日志
 * @param string $type 操作类型 login add edit view delete
 * @param int    $param_id 操作类型
 * @param array  $param 提交的参数
 */
function add_log($type, $param_id = '', $param = [])
{
    $request = get_params();
    switch ($type) {
        case 'login':
            $title = '登录';
            break;
        case 'upload':
            $title = '上传';
            break;
        case 'add':
            $title = '新增';
            break;
        case 'edit':
            $title = '编辑';
            break;
        case 'view':
            $title = '查看';
            break;
        case 'delete':
            $title = '删除';
            break;
        case 'check':
            $title = '审核';
            break;
        default:
            $title = '未知';
            break;
    }
    if ($type == 'login') {
        $login_admin = \think\facade\Db::name('Admin')->where(array('id' => $param_id))->find();
    } else {
        $session_admin = get_config('app.session_admin');
        $login_admin = \think\facade\Session::get($session_admin);
    }
    $data = [];
    $data['uid'] = $login_admin['id'];
    $data['nickname'] = $login_admin['nickname'];
    $data['type'] = $type;
    $data['param_id'] = $param_id;
    $data['param'] = json_encode($param);
    $data['module'] = \think\facade\App::initialize()->http->getName();
    $data['controller'] = strtolower(app('request')->controller());
    $data['function'] = app('request')->action();
    $parameter = $data['module'] . '/' . $data['controller'] . '/' . $data['function'];
    $data['rule_menu'] = $parameter;
    $data['title'] = \think\facade\Db::name('AdminRule')->where(array('src' => $parameter))->value('title') ?? $title;
    $content = $login_admin['nickname'] . '在' . date('Y-m-d H:i:s') . '执行了' . $data['title'] . '操作';
    $data['content'] = $content;
    $data['ip'] = app('request')->ip();
    $data['create_time'] = time();
    \think\facade\Db::name('AdminLog')->strict(false)->field(true)->insert($data);
}